//
//  SelectAddressTool.m
//  JinFuThree
//
//  Created by 毛韶谦 on 2018/9/4.
//  Copyright © 2018年 毛韶谦. All rights reserved.
//

#import "SelectAddressTool.h"
#import "addressCell.h"

@interface SelectAddressTool ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *mainScrollView;
@property (nonatomic, strong) UITableView *provinceTableView;
@property (nonatomic, strong) UITableView *cityTableView;
@property (nonatomic, strong) UITableView *districtTableView;
@property (nonatomic, strong) UIScrollView *topScrollView;
@property (nonatomic, strong) UIImageView *lineImageView;
@property (nonatomic, strong) UILabel *showProvinceLabel;
@property (nonatomic, strong) UILabel *showCityLabel;
@property (nonatomic, strong) UILabel *showDistrictLabel;
@property (nonatomic, strong) NSMutableArray <AddressModel *>*mutArr;

@property (nonatomic, strong) NSIndexPath *provinceIndexPath;
@property (nonatomic, strong) NSIndexPath *cityIndexPath;
@property (nonatomic, strong) NSIndexPath *districtIndexPath;

@end

@implementation SelectAddressTool

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        
        self.mainScrollView.contentSize = CGSizeMake(ScreenWidthMao*3, 400 - 55);
        
        self.provinceIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        self.cityIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        self.districtIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        
        self.provinceTableView.backgroundColor = [UIColor whiteColor];
        self.cityTableView.backgroundColor = [UIColor whiteColor];
        self.districtTableView.backgroundColor = [UIColor whiteColor];
        
        [self.showProvinceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.topScrollView.mas_top).offset(4);
            make.bottom.mas_equalTo(self.topScrollView);
            make.left.mas_equalTo(self.topScrollView.mas_left).offset(20);
            make.height.mas_equalTo(51);
            make.width.mas_lessThanOrEqualTo(70);
        }];
        [self.showCityLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.topScrollView.mas_top).offset(4);
            make.bottom.mas_equalTo(self.topScrollView);
            make.left.mas_equalTo(self.showProvinceLabel.mas_right).offset(20);
            make.width.mas_lessThanOrEqualTo(70);
        }];
        [self.showDistrictLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.topScrollView.mas_top).offset(4);
            make.right.bottom.mas_equalTo(self.topScrollView);
            make.left.mas_equalTo(self.showCityLabel.mas_right).offset(20);
            make.width.mas_lessThanOrEqualTo(70);
        }];
        
        self.lineImageView.frame = CGRectMake(20, 54, 42, 1);
        
        UIImageView *lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15, 55, ScreenWidthMao - 30, 0.7f)];
        lineImageView.backgroundColor = ThemeMaoLineColor;
        [self addSubview:lineImageView];
        
        
        
        NSArray *tempArr = [AD_UserDefaults objectForKey:ASJF_Area];
        if (!tempArr) {
            
            [HFQIndicationView showInView:self];
            NSString *url = [Common ServicesURL:@"as/app/financial/location/provinceCityDistrict"];
            [[RequestManager manager] HFQDataRequest_Mao:RequestMethodGet URLString:url parameters:nil success:^(id  _Nullable responseObject) {
                [HFQIndicationView dismiss];
                NSDictionary *dataDic = responseObject;
                if ([[NSString stringWithFormat:@"%@",dataDic[@"code"]] isEqualToString:@"200"]){
                    [AD_UserDefaults setObject:[dataDic objectForKey:@"data"] forKey:ASJF_Area];
                    [AD_UserDefaults synchronize];
                    NSArray *tempArr = [AD_UserDefaults objectForKey:ASJF_Area];
                    for (NSDictionary *dic in tempArr) {
                        AddressModel *model = [[AddressModel alloc] init];
                        [model setValuesForKeysWithDictionary:dic];
                        model.isSelect = @"0";
                        [self.mutArr addObject:model];
                    }
                    [self.provinceTableView reloadData];
                }
            } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
                [HFQIndicationView dismiss];
            }];
        }else {
            for (NSDictionary *dic in tempArr) {
                AddressModel *model = [[AddressModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                model.isSelect = @"0";
                [self.mutArr addObject:model];
            }
            [self.provinceTableView reloadData];
        }
    }
    return self;
}


#pragma mark tableView代理方法


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.mutArr.count) {
        if ([tableView isEqual:self.provinceTableView]) {
            
            return self.mutArr.count;
        }else if ([tableView isEqual:self.cityTableView]) {
            
            AddressModel *cityModel = self.mutArr[self.provinceIndexPath.row];
            return cityModel.children.count;
        }else if ([tableView isEqual:self.districtTableView]) {
            
            AddressModel *cityModel = self.mutArr[self.provinceIndexPath.row];
            AddressModel *disModel = cityModel.children[self.cityIndexPath.row];
            return disModel.children.count;
        }
    }
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 55;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.01f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    addressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"addressCell"];
    if (!cell) {
        cell = [[addressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"addressCell"];
        cell.backgroundColor = [UIColor whiteColor];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if ([tableView isEqual:self.provinceTableView]) {
        
        AddressModel *model = self.mutArr[indexPath.row];
        [cell updateInfoCellWithModel:model];
    }else if ([tableView isEqual:self.cityTableView]) {
        
        AddressModel *cityModel = self.mutArr[self.provinceIndexPath.row];
        AddressModel *model = cityModel.children[indexPath.row];
        [cell updateInfoCellWithModel:model];
    }else if ([tableView isEqual:self.districtTableView]) {
        
        AddressModel *cityModel = self.mutArr[self.provinceIndexPath.row];
        AddressModel *disModel = cityModel.children[self.cityIndexPath.row];
        AddressModel *model = disModel.children[indexPath.row];
        [cell updateInfoCellWithModel:model];
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView *view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if ([tableView isEqual:self.provinceTableView]) {
        //添加选择的省份
        self.provinceIndexPath = indexPath;
        self.cityIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        self.districtIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        
        AddressModel *model = self.mutArr[self.provinceIndexPath.row];
        for (AddressModel *tempModel in self.mutArr) {
            tempModel.isSelect = @"0";
        }
        model.isSelect = @"1";
        [tableView reloadData];
        [self.cityTableView reloadData];
        
        self.showProvinceLabel.text = model.label;
        self.showProvinceLabel.accessibilityLabel = model.value;
        self.showCityLabel.text = @"请选择";
        self.showDistrictLabel.text = @"";
        
        [self layoutIfNeeded];
        [self.mainScrollView setContentOffset:CGPointMake(ScreenWidthMao, 0) animated:YES];
    }else if ([tableView isEqual:self.cityTableView]) {
        self.cityIndexPath = indexPath;
        self.districtIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        
        AddressModel *model = self.mutArr[self.provinceIndexPath.row];
        AddressModel *cityModel = model.children[self.cityIndexPath.row];
        for (AddressModel *tempModel in model.children) {
            tempModel.isSelect = @"0";
        }
        cityModel.isSelect = @"1";
        [tableView reloadData];
        [self.districtTableView reloadData];
        
        self.showCityLabel.text = cityModel.label;
        self.showCityLabel.accessibilityLabel = cityModel.value;
        self.showDistrictLabel.text = @"请选择";
        
        [self layoutIfNeeded];
        [self.mainScrollView setContentOffset:CGPointMake(ScreenWidthMao*2.f, 0) animated:YES];

    }else if ([tableView isEqual:self.districtTableView]) {
        self.districtIndexPath = indexPath;
        
        AddressModel *model = self.mutArr[self.provinceIndexPath.row];
        AddressModel *cityModel = model.children[self.cityIndexPath.row];
        AddressModel *disModel = cityModel.children[self.districtIndexPath.row];
        for (AddressModel *tempModel in cityModel.children) {
            tempModel.isSelect = @"0";
        }
        disModel.isSelect = @"1";
        [tableView reloadData];
        
        self.showDistrictLabel.text = disModel.label;
        self.showDistrictLabel.accessibilityLabel = disModel.value;
        
        [self layoutIfNeeded];
        [UIView animateWithDuration:0.3f animations:^{
            self.lineImageView.frame = CGRectMake(CGRectGetMinX(self.showDistrictLabel.frame), 54, CGRectGetWidth(self.showDistrictLabel.frame), 1);
        }];
    }
    if ([self.delegate respondsToSelector:@selector(selectAddressProvince:City:District:)]) {
        [self.delegate selectAddressProvince:self.showProvinceLabel City:self.showCityLabel District:self.showDistrictLabel];
    }
    
}



- (void)clickShowLabel:(UITapGestureRecognizer *)gesture {
    
    UILabel *label = (UILabel *)gesture.view;
    if ([label.text isEqualToString:@""]) {
        return;
    }
    switch (label.tag) {
        case 1:
        {
            [self.mainScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
            break;
        case 2:
        {
            [self.mainScrollView setContentOffset:CGPointMake(ScreenWidthMao, 0) animated:YES];
        }
            break;
        case 3:
        {
            [self.mainScrollView setContentOffset:CGPointMake(ScreenWidthMao*2.f, 0) animated:YES];
        }
            break;
        default:
            break;
    }
}

#pragma mark -----scrollView代理方法

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if ([scrollView isEqual:self.mainScrollView]) {
        
        if (scrollView.contentOffset.x < ScreenWidthMao) { //省
            
            if ([self.showProvinceLabel.text isEqualToString:@"请选择"] || [self.showProvinceLabel.text isEqualToString:@""]) {
                scrollView.contentOffset = CGPointMake(0, 0);
            }
            CGFloat maxX = CGRectGetMinX(self.showCityLabel.frame);
            CGFloat minX = CGRectGetMinX(self.showProvinceLabel.frame);
            
            self.lineImageView.frame = CGRectMake((maxX - minX)/ScreenWidthMao * scrollView.contentOffset.x + minX, 54, CGRectGetWidth(self.lineImageView.frame), 1);
            
        }else if ( ScreenWidthMao <= scrollView.contentOffset.x < ScreenWidthMao * 2.f) { //市
            
            if ([self.showCityLabel.text isEqualToString:@"请选择"] || [self.showCityLabel.text isEqualToString:@""]) {
                scrollView.contentOffset = CGPointMake(ScreenWidthMao, 0);
            }
            CGFloat maxX = CGRectGetMinX(self.showDistrictLabel.frame);
            CGFloat minX = CGRectGetMinX(self.showCityLabel.frame);
            
            self.lineImageView.frame = CGRectMake((maxX - minX)/ScreenWidthMao * (scrollView.contentOffset.x - ScreenWidthMao) + minX, 54, CGRectGetWidth(self.lineImageView.frame), 1);
            
        }else {
            
        }
        
        if (scrollView.contentOffset.x == 0.0f) { //省
            [UIView animateWithDuration:0.1f animations:^{
                self.lineImageView.frame = CGRectMake(CGRectGetMinX(self.showProvinceLabel.frame), 54, CGRectGetWidth(self.showProvinceLabel.frame), 1);
            }];
        }else if ( ScreenWidthMao == scrollView.contentOffset.x) { //市
            [UIView animateWithDuration:0.1f animations:^{
                self.lineImageView.frame = CGRectMake(CGRectGetMinX(self.showCityLabel.frame), 54, CGRectGetWidth(self.showCityLabel.frame), 1);
            }];
        }else if (scrollView.contentOffset.x == ScreenWidthMao * 2.f) {  //区
            [UIView animateWithDuration:0.1f animations:^{
                self.lineImageView.frame = CGRectMake(CGRectGetMinX(self.showDistrictLabel.frame), 54, CGRectGetWidth(self.showDistrictLabel.frame), 1);
            }];
        }
        
        NSLog(@"%f",scrollView.contentOffset.x);
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if ([scrollView isEqual:self.mainScrollView]) {
        
        
    }
}


- (UIScrollView *)mainScrollView {
    
    if (!_mainScrollView) {
        _mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 55, ScreenWidthMao, 400 - 55)];
        _mainScrollView.showsVerticalScrollIndicator = NO;
        _mainScrollView.showsHorizontalScrollIndicator = NO;
        _mainScrollView.delegate = self;
        _mainScrollView.pagingEnabled = YES;
        _mainScrollView.alwaysBounceVertical = NO;
        _mainScrollView.alwaysBounceHorizontal = YES;
        
        [self addSubview:_mainScrollView];
    }
    return _mainScrollView;
}

- (UITableView *)provinceTableView {
    
    if (!_provinceTableView) {
        _provinceTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidthMao, 400 - 55) style:UITableViewStyleGrouped];
        _provinceTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _provinceTableView.delegate = self;
        _provinceTableView.dataSource = self;
        
        [self.mainScrollView addSubview:_provinceTableView];
    }
    return _provinceTableView;
}
- (UITableView *)cityTableView {
    
    if (!_cityTableView) {
        _cityTableView = [[UITableView alloc] initWithFrame:CGRectMake(ScreenWidthMao, 0, ScreenWidthMao, 400 - 55) style:UITableViewStyleGrouped];
        _cityTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _cityTableView.delegate = self;
        _cityTableView.dataSource = self;
        
        [self.mainScrollView addSubview:_cityTableView];
    }
    return _cityTableView;
}
- (UITableView *)districtTableView {
    
    if (!_districtTableView) {
        _districtTableView = [[UITableView alloc] initWithFrame:CGRectMake(ScreenWidthMao*2.f, 0, ScreenWidthMao, 400 - 55) style:UITableViewStyleGrouped];
        _districtTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _districtTableView.delegate = self;
        _districtTableView.dataSource = self;
        
        [self.mainScrollView addSubview:_districtTableView];
    }
    return _districtTableView;
}

- (UIScrollView *)topScrollView {
    
    if (!_topScrollView) {
        _topScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidthMao - 80, 55)];
        _topScrollView.showsVerticalScrollIndicator = NO;
        _topScrollView.showsHorizontalScrollIndicator = NO;
        _topScrollView.alwaysBounceVertical = NO;
        _topScrollView.alwaysBounceHorizontal = YES;
        
        [self addSubview:_topScrollView];
    }
    return _topScrollView;
}

- (UIImageView *)lineImageView {
    
    if (!_lineImageView) {
        _lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 54, 60, 1)];
        _lineImageView.backgroundColor = HexColor(0x333333);
        
        [self.topScrollView addSubview:_lineImageView];
    }
    return _lineImageView;
}

- (UILabel *)showProvinceLabel {
    
    if (!_showProvinceLabel) {
        _showProvinceLabel = [[UILabel alloc] init];
        _showProvinceLabel.textColor = HexColor(0x333333);
        _showProvinceLabel.font = [UIFont systemFontOfSize:14];
        _showProvinceLabel.userInteractionEnabled = YES;
        _showProvinceLabel.text = @"请选择";
        _showProvinceLabel.tag = 1;
        
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickShowLabel:)];
        [_showProvinceLabel addGestureRecognizer:gesture];
        
        [self.topScrollView addSubview:_showProvinceLabel];
    }
    return _showProvinceLabel;
}
- (UILabel *)showCityLabel {
    
    if (!_showCityLabel) {
        _showCityLabel = [[UILabel alloc] init];
        _showCityLabel.textColor = HexColor(0x333333);
        _showCityLabel.font = [UIFont systemFontOfSize:14];
        _showCityLabel.userInteractionEnabled = YES;
        _showCityLabel.tag = 2;
        
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickShowLabel:)];
        [_showCityLabel addGestureRecognizer:gesture];
        
        [self.topScrollView addSubview:_showCityLabel];
    }
    return _showCityLabel;
}
- (UILabel *)showDistrictLabel {
    
    if (!_showDistrictLabel) {
        _showDistrictLabel = [[UILabel alloc] init];
        _showDistrictLabel.textColor = HexColor(0x333333);
        _showDistrictLabel.userInteractionEnabled = YES;
        _showDistrictLabel.font = [UIFont systemFontOfSize:14];
        _showDistrictLabel.tag = 3;
        
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickShowLabel:)];
        [_showDistrictLabel addGestureRecognizer:gesture];
        
        [self.topScrollView addSubview:_showDistrictLabel];
    }
    return _showDistrictLabel;
}

- (NSMutableArray *)mutArr {
    
    if (!_mutArr) {
        _mutArr = [NSMutableArray array];
    }
    return _mutArr;
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
